package com.direct.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.hibernate.annotations.Parent;

import com.direct.common.DateUtils;
import com.direct.dao.AccountDao;
import com.direct.domian.Account;
import com.direct.domian.Power;
import com.direct.domian.Role;
import com.direct.exception.LoginEXception;
import com.direct.service.AccountService;

public class AccountServiceImpl implements AccountService {
	private AccountDao accountDao;

	public void setAccountDao(AccountDao accountDao) {
		this.accountDao = accountDao;
	}

	@Override
	public Account querySingle(Account account) throws LoginEXception {
		Account dbAccount = null;
		try {
			// 通过账号查询员工是否存在
			String hql = "select a from Account a where a.username=?";
			Object params[] = new Object[] { account.getUsername() };
			dbAccount = accountDao.querySingle(hql, params);
			if(dbAccount!=null){
				List<Power> ps = new ArrayList<Power>();
				Set<Role> role =dbAccount.getRoles();
				for (Role r : role) {
					Set<Power> p = r.getPowers();
					for (Power power : p) {
						//如果为一级权限
						if(power.getPower()==null){
							ps.add(power);
						}
					}
					for (Power pp : ps) {
						Set<Power> sonPowers =new HashSet<Power>();
						for (Power power : p) {
							//二级权限
							if(power.getPower()!=null){
								Power parent = power.getPower();
								if(parent.equals(pp)){
									sonPowers.add(power);
								}
							}
						}
						pp.setPowers(sonPowers);
					}
				}
				dbAccount.setPower(ps);
			}
		} catch (RuntimeException e) {
			e.printStackTrace();
			throw new LoginEXception("数据库连接出错", e);
		}
		// 如果账户不存在
		if (dbAccount == null) {
			throw new LoginEXception("账户不存在");
		}
		// 如果是密码错误
		if (!account.getPassword().equals(dbAccount.getPassword())) {
			throw new LoginEXception("密码错误");
		}
		// 如果上次登陆是今天之前，则重置密码错误次数
		if (dbAccount.getLastTime().getTime() < DateUtils.getToday().getTime()) {
			dbAccount.setErrorCount(0);
		}
		// 修改登陆时间为当前时间
		dbAccount.setLastTime(new Date());
		if (dbAccount.getErrorCount() > 3) {
			new LoginEXception("登录错误次数超过3次,请明天再试!");
		}
		// 如果用户存在查询他所具有的权限

		return dbAccount;
	}
}
